package pachube.andorid;


import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

import org.apache.http.HttpConnection;

import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TabHost;



public class Login extends Activity {
	private ImageButton loginBtn;
	ProgressDialog myProgressDialog = null;
	EditText username;
	EditText password;
	EditText feed;
	Handler hdl;
	
	boolean live;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        loginBtn = (ImageButton)this.findViewById(R.id.widget48);
        //loginBtn.setAlpha(255);
        username = (EditText)this.findViewById(R.id.widget47);
        password = (EditText)this.findViewById(R.id.widget50);
        feed = (EditText)this.findViewById(R.id.widget45);
        
        SharedPreferences settings = getSharedPreferences("MyPrefsFile", 0);
        String user = settings.getString("username", "0");
        String pass = settings.getString("password", "0");
        String fID = settings.getString("feed", "0");
        
        
        if(!user.equals("0")) {
        	username.setText(user);
        }
        
        if(!pass.equals("0")) {
        	password.setText(pass);
        }
        if(!fID.equals("0")) {
        	feed.setText(fID);
        }
        
        
        Bundle extras = getIntent().getExtras(); 
        String flag  = extras.getString("flag");
        if(flag.equals("false")) {
        	AlertDialog  alertDialog = new AlertDialog.Builder(this).create();

            alertDialog.setTitle("Login Error");

            alertDialog.setMessage("Please check your credential or Internet connection");

            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog, int which) {

                return;

            } });
        }
        
        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	//hdl = new Handler();
            	//Thread thread = new Thread(Application.this);
				//thread.start();
            	
            	//Make a runnable
            	
            	Runnable myRunnable= new Runnable(){
                            @Override
                            public void run(){
                            	Looper.prepare();
                            	//toogleFetchBtn(false);
                            	
                            	int fetch = fetchData(username.getText().toString(), password.getText().toString(), feed.getText().toString());
                    			
                    			if (fetch==0) {
                    				
                    				myProgressDialog.dismiss();
                    				
                    				Intent errorLogin = new Intent(Login.this, Login.class);
                    				errorLogin.putExtra("flag", "false");
                    				
                    	        	startActivityForResult(errorLogin, 0);
                    				
                    				
                    				
                    			}
                    			else {
                    				myProgressDialog.dismiss();
                    				
                    				
                    				//keep it:
                    				final String PREFS_NAME = "MyPrefsFile";
                    				SharedPreferences settings;
                    				SharedPreferences.Editor editor;
                    				settings = getSharedPreferences(PREFS_NAME, 0);
                    				editor = settings.edit();
                    				editor.putString("username", username.getText().toString());
                    				editor.putString("password", password.getText().toString());
                    				editor.putString("feed", feed.getText().toString());
                    				editor.commit();
                    				
                    				
                    				Intent feedata = new Intent(Login.this, main.class);
                    				feedata.putExtra("feed", feed.getText().toString());
                    				feedata.putExtra("live", live);
                    	        	startActivityForResult(feedata, 1);
                    	        	//toogleFetchBtn(true);
                    			}
                                
                            }
                        };
                        

            //open up you dialog
                myProgressDialog = ProgressDialog.show(Login.this,"PachubeViewer", "fetching data...", true);
              //initialize your thread  
                Thread thread =  new Thread(null, myRunnable, "FetchData");
                thread.start();
            }
        });
        
        
        
    }
    
    void toogleFetchBtn(boolean state) {
    	if(state) {
    		loginBtn.setEnabled(true);
    	}
    	else {
    		loginBtn.setEnabled(false);
    	}
    }
    
    int fetchData(String username, String password, String feedID) {
    	int a = 0;
    	
    	if(username.length()>0 && password.length()>0 && feedID.length()>0)
    		a = runJSONParser(feedID, username, password);
    	return a;
    }
    
public InputStream getJSONData(String url, final String user, final String pass){
        
    	InputStream data = null;
    	try {
        Authenticator.setDefault(new Authenticator(){
		    protected PasswordAuthentication getPasswordAuthentication() {
		        return new PasswordAuthentication(user,pass.toCharArray());
		    }});
        
        
        
		HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
		/*c.setRequestProperty(
	               "Authorization",
	               "basic " +  	android.util.Base64.encode((user+":"+pass).getBytes(), android.util.Base64.DEFAULT)
	              );*/
		c.setUseCaches(false);
		c.connect();
		
		data = c.getInputStream();
		//System.out.println(readInputStreamAsString(data));
		//Log.i("AUTH", readInputStreamAsString(data));
    	} catch (Exception e) {
    		Log.i("AUTH", "NOT Authenticated");
            e.printStackTrace();
        }
        
        return data;
    }

public static String readInputStreamAsString(InputStream in) throws IOException {

BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
  byte b = (byte)result;
  buf.write(b);
  result = bis.read();
}        
return buf.toString();
}
    
    
    public int runJSONParser(String feed, String username, String password){
        try{
        Log.i("MY INFO", "Json Parser started..");
        Gson gson = new Gson();
        Reader r = new InputStreamReader(getJSONData("http://api.pachube.com/v2/feeds/"+feed+".json", username, password));
        if(r==null) return 0;
        else {
        EEML objs = gson.fromJson(r, EEML.class);
        Log.i("MY INFO", ""+objs.getDescription());
        Log.i("MY INFO", ""+objs.getLocation());
        
        Log.i("MY INFO", ""+objs.getStatus());
        Log.i("MY INFO", ""+objs.getUpdated());
        Log.i("MY INFO", ""+objs.getDatastreams().size());
        
        final String PREFS_NAME = "MyPrefsFile";
		SharedPreferences settings;
		SharedPreferences.Editor editor;
		settings = getSharedPreferences(PREFS_NAME, 0);
		editor = settings.edit();
		editor.putString("description", objs.getDescription());
		editor.putString("status", objs.getStatus());
		if(objs.getStatus().equals("live")) {
			live = true;
		}else {
			live = false;
		}
		editor.putString("updated", objs.getUpdated());
		editor.putString("size", ""+objs.getDatastreams().size());
		editor.putString("domain", ""+objs.getLocation().getDomain());
		editor.putString("lat", ""+objs.getLocation().getLat());
		editor.putString("lon", ""+objs.getLocation().getLon());
		//editor.commit();
        
        String[] tags;
        String allTags = "";
        int counter = 0;
        String unit;
        for(datastream dt : objs.getDatastreams()){
        	allTags = "";
        	if(dt.getUnits()==null) {
        		unit = "";
        	}
        	else {
        		unit = dt.getUnits().label;
        	}
            Log.i("Datastream", dt.getCurrent_Value() + " - " + unit);
            editor.putString(""+dt.getID(), dt.getCurrent_Value() + " - " + unit);
            editor.putString("Min"+dt.getID(), dt.getMin_Value());
            editor.putString("Max"+dt.getID(), dt.getMax_Value());
            editor.putString("D"+counter, dt.getID());
            
            tags = dt.getTags();
            if(tags!=null) {
            for(int i=0;i<tags.length-1;i++) {
            	allTags += tags[i]+", ";
            }
            allTags += tags[tags.length-1];
            }
            else {
            	allTags = "";
            }
            
            editor.putString("Tag"+counter, allTags);
            counter++;
            
        }
        
        editor.commit();
        //loginBtn.setEnabled(true);
        return 1;
        }
        }catch(Exception ex){
            ex.printStackTrace();
            return 0;
        }
 
    }

}
